<?php
	require_once('paths.inc');
	require_once(INCLUDE_PATH.'constants.inc');
	require_once('page.inc');
	require_once(DB_PATH.'db.inc');
	
	require_once('security.inc');
	require_once('utils.inc');
	
	session_start();

	check_permissions(CT_PERM_PLATI);
	//get a db connection handle
	$db = db_connect();
	$tipPlata = $_GET['tip'];
	
	$tipPlata == CT_PLATA_PLATA      ?  $stareKind 	= "stare_plata_exec" : $stareKind 	= "stare_incasare_sol";
	$stareKind == "stare_plata_exec" ? 	$sumaKind 	= "suma_totala_exec" : $sumaKind 	= "suma_totala_sol";
	$stareKind == "stare_plata_exec" ? 	$sumaKind 	= "suma_totala_exec" : $sumaKind 	= "suma_totala_sol";
	$stareKind == "stare_plata_exec" ? 	$nrComanda 	= "nr_comanda_exec"  : $nrComanda 	= "nr_comanda_sol";
	$stareKind == "stare_plata_exec" ? 	$moneda 	= "moneda_exec" 	 : $moneda 		= "moneda_sol";
	
	$idUser = $_SESSION['user_logat']->id_user;
	
	if (isset($_POST['add_plati_incasari'])) {										
		//inseram platile sau incasarile	
		$data = $_POST['data_plata'];        
		try {	
			$db->beginTransaction();				
			for ($i = 0; $i < count($_SESSION['idComanda']); $i++) {				
				$comanda = LightComanda::queryLightLoadByID($db, $_SESSION['idComanda'][$i], $_SESSION['client_logat']->id_client, $moneda);
				
                //creeam obiectul plata!!//de facut cu moneda!!!
                $restDePlatit = $_SESSION['statusAndSuma'][$i][$sumaKind] - $_SESSION['valoarePlataPartiala'][$i];
				$plata = new PlatiComanda($_SESSION['idComanda'][$i], $idUser, $tipPlata, $comanda->moneda, $restDePlatit, $data);
				$plata->queryInsert($db);
											
				//aici trebuie sa schimbam statusul comenzii din platita/incasata partial in plata completa
				//efectiv schimbam unul din cele 2 campuri: stare_incasare_sol, stare_plata_exec
                //print_r_html($comanda);

				$comanda->updateStare($db, $stareKind, 2, $_SESSION['idComanda'][$i]);												
			}
			$db->commit();
			notice_msg("LANG_Plati_Incasari_Efectuare_Succes", "show_comenzi.php");
		}
		catch (QueryInsertPlatiComandaException $e) {			   
			$db->rollBack();		//maybe NOT needed ????        	
        	redirectOnError(CT_ADD_PLATI_INSERT_PLATI_COMANDA);
		}
		catch (QueryUpdateStareException $e) {
			$db->rollBack();		//maybe NOT needed ????        	
        	redirectOnError(CT_ADD_PLATI_COMANDA_UPDATE_STARE);
		}
		catch (QueryUpdatePlatiComandaException $e) {
			redirectOnError(CT_ADD_PLATI_UPDATE_PLATI_COMANDA);
		}		
	
		unset($_SESSION['statusAndSuma']);
		unset($_SESSION['valoarePlataPartiala']);
		unset($_SESSION['idComanda']);		
		//end inserare plati sau incasari		
	}
	else {
		html_header("LANG_Adauga_comanda", "calendar", "add_plati");
		select_js_language();
		
		if ($tipPlata == 1) {			
			$linkuri = array(LANG_Home => "home.php", LANG_Plati => "view_plata.php", LANG_EFECTUARE_PLATI => "");
			titlu_pagina($linkuri);			
						
			$titluTabel = LANG_EFECTUARE_PLATI;			
			$plataAnterioara = LANG_TOTAL_PLATIT_ANTERIOR;
			$restPlata = LANG_REST_PLATA;
		}
		else {
			$linkuri = array(LANG_Home => "home.php", LANG_Incasari => "view_incasare.php", LANG_EFECTUARE_INCASARI => "");
			titlu_pagina($linkuri);			
			$titluTabel = LANG_EFECTUARE_INCASARI;
			$plataAnterioara = LANG_TOTAL_INCASAT_ANTERIOR;
			$restPlata = LANG_REST_INCASARE;
		}
	
		$tabel = '<div class="container"><table id="wrapper" align="left">
					<thead>
						<tr>
							<th colspan="5"> ' . $titluTabel . '
						</tr>
					</thead>
					<tr class="capTabel">
						<th>' . LANG_NR_COMANDA . '</th>	
						<th>' . LANG_TOTAL . '</th>	
						<th>' . $plataAnterioara . '</th>	
						<th>' . LANG_TOTAL_DE_PLATIT_ACUM . '</th>
						<th>' . LANG_Moneda . '</th>
					</tr>';					  		
		
		$tipPlata = $_GET['tip'];
		$idComanda = $_GET['id_comanda'];
		
		//verificam daca ID-urile corespund id_client-ului corespunzator
		try {
			Comanda::checkProprietaryIDs($db, $idComanda, $_SESSION['user_logat']->id_client);			
		}
		catch (QueryCheckProprietaryIDsException $e) {
			redirectOnError(CT_ADD_PLATI_CHECK_PROPRIETARY_IDS);
		}
		catch (comandaIDfromPlatiComandaBadUrlException $e) {
			redirectOnError(CT_ADD_PLATI_COMANDA_ID_FROM_PLATI_COMANDA_BAD_URL);
		}
		//end verificare
		
		//break the IDs and get an array
		$buffer = explode("_", $idComanda);
		$idComanda = $buffer; // <= array	
		//end break the IDs and get an array		
		
		$statusAndSuma = array();	
		$valoarePlataPartiala = array();
				
		for ($i = 0; $i < count($idComanda); $i++) {			
			try {	
				$statusAndSuma[$i] = Comanda::getStatusAndSumaKind($db, $idComanda[$i], $stareKind, $sumaKind, $nrComanda, $moneda);
				//setam starea platii pe 0, adica neplatita; 0 - neplatita, 1 - partial, 2 - platita
				$plataStatus = 0;
								
				//daca avem de a face cu o comanda care nu este platita deloc
				if ($statusAndSuma[$i][$stareKind] == 0) {
					$tabel .= '<tr onmouseout=this.className="whiteThing" onmouseover=this.className="blueThing" class="whiteThing">
								<td>' . $statusAndSuma[$i][$nrComanda] . '</td>
								<td>' . $statusAndSuma[$i][$sumaKind] . '</td>
								<td>0</td>
								<td>' . $statusAndSuma[$i][$sumaKind] . '</td>
								<td>' . $currencies[$statusAndSuma[$i][$moneda]] . '</td>
							   </tr>';
				}

				//daca avem de a face cu o comanda care este platita partial
				if ($statusAndSuma[$i][$stareKind] == 1) {
					//facem un calcul sa vedem cat mai are de platit si cat este deja platit
					//pe baza tipului comenzii stabilim tipul platii pe baza caruia vom facem cautarea
					$valoarePlataPartiala[$i] = PlatiComanda::getPlataStatusForComanda($db, $idComanda[$i], $tipPlata, $_SESSION['user_logat']->id_client);
					//end calcul
					if ($valoarePlataPartiala[$i] < $statusAndSuma[$i][$sumaKind]) {
						$tabel .= '<tr onmouseout=this.className="whiteThing" onmouseover=this.className="blueThing" class="whiteThing">
									<td>' . $statusAndSuma[$i][$nrComanda] . '</td>
									<td>' . $statusAndSuma[$i][$sumaKind] . '</td>
									<td>' . $valoarePlataPartiala[$i] . '</td>
									<td>' . ($statusAndSuma[$i][$sumaKind] - $valoarePlataPartiala[$i]) . '</td>
									<td>' . $currencies[$statusAndSuma[$i][$moneda]] . '</td>
								   </tr>';
					}
					else {
						//asa ceva nu se poate.... daca se intampla asa insemna ca noi avem erori in logica programului
						//cel mai probabil aici inchidem serveru !!!
					}
				}
				
				//daca avem de a face cu o comanda care este platita integral.... pentru ea nu facem nimic
				if ($statusAndSuma[$i][$stareKind] == 2) {
                    $valoarePlataPartiala[$i] = 0;
					$tabel .= '<tr onmouseout=this.className="whiteThing" onmouseover=this.className="blueThing" class="whiteThing">
								<td>' . $statusAndSuma[$i][$nrComanda] . '</td>
								<td>' . $statusAndSuma[$i][$sumaKind] . '</td>
								<td>' . $statusAndSuma[$i][$sumaKind] . '</td>
								<td>0</td>
								<td>' . $currencies[$statusAndSuma[$i][$moneda]] . '</td>
							   </tr>';
				}
			}
			catch (QueryGetStatusComandaException $e) {
				redirectOnError(CT_ADD_PLATI_GET_STATUS_FOR_COMANDA);
			}
			catch (getPlataStatusForComandaException $e) {
				redirectOnError(CT_ADD_PLATI_GET_PLATA_STATUS_FOR_COMANDA);
			}
		}
		echo $tabel;
		?>
			<tr class="capTabel">
				<td colspan="5" align="center">
					<form name="form_add_plata" action="add_plati.php?tip=<?php echo $tipPlata; ?>" method="POST">
						<?php echo LANG_DATA; ?>
						<input type="text" name="data_plata" class="input_date" readonly="readonly" value="<?php echo date("Y-n-j"); ?>" />
						<input 
							type="image" 
							src="<?php echo IMG_PATH . "calendar3.gif"; ?>"
							title="<?php echo LANG_Data_tr_acte_sol; ?>"
							alt="<?php echo LANG_Select_date; ?>"
							onclick="displayCalendar(document.form_add_plata.data_plata,'yyyy-mm-dd',this,true,'main');return false" />
                        
                        <div class="container">
                        <?php
                            if ($tipPlata == 1)
                                buton_final_ok(LANG_ADD_PLATI, "add_plati_incasari");
                            else
                                buton_final_ok(LANG_ADD_INCASARI, "add_plati_incasari");                
                            echo '&nbsp;&nbsp;';
                            buton_final_cancel(LANG_CANCEL, "show_comenzi.php");
                        ?>
                        </div>
                    </form>
				</td>
			</tr>
	</table>
	</div>

	<?php
		
		//setam sesiunile
		$_SESSION['statusAndSuma'] = $statusAndSuma;
		$_SESSION['valoarePlataPartiala'] = $valoarePlataPartiala;
		$_SESSION['idComanda'] = $idComanda;
		//end setam sesiunile
	}
	html_footer();
?>